from dataclasses import dataclass
from typing import TypeVar, Generic, Optional
from .ErrorCode import ErrorCode
T = TypeVar('T')


@dataclass
class BaseResponse(Generic[T]):
    """
    通用返回类

    作者: 程序员鱼皮
    来源: 编程导航知识星球
    """

    code: int
    data: Optional[T] = None
    message: str = ""

    def __init__(self, code: int, data: Optional[T] = None, message: str = ""):
        self.code = code
        self.data = data
        self.message = message

    @classmethod
    def from_error_code(cls, error_code: 'ErrorCode') -> 'BaseResponse[T]':
        """
        通过ErrorCode创建BaseResponse实例

        :param error_code: 错误码对象
        :return: BaseResponse实例
        """
        return cls(code=error_code.code, data=None, message=error_code.message)


# # 示例使用
# def some_api_function():
#     # 假设某个业务逻辑返回了一个BaseResponse实例
#     base_response = BaseResponse(code=ErrorCode.SUCCESS.code, data={"key": "value"}, message=ErrorCode.SUCCESS.message)
#
#     # 使用ApiResponse返回成功响应
#     return ApiResponse.success(message=base_response.message, data=base_response.data)
#
#
# def another_api_function():
#     # 假设某个业务逻辑返回了一个错误
#     error_response = BaseResponse.from_error_code(ErrorCode.NOT_FOUND_ERROR)
#
#     # 使用ApiResponse返回错误响应
#     return ApiResponse.error(code=error_response.code, message=error_response.message)

